package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.*;
import cn.wolfcode.wms.mapper.ProductStockMapper;
import cn.wolfcode.wms.mapper.StockIncomeBillItemMapper;
import cn.wolfcode.wms.mapper.StockIncomeBillMapper;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IStockIncomeBillService;
import cn.wolfcode.wms.util.PageResult;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class StockIncomeBillServiceImpl implements IStockIncomeBillService {
    @Autowired
    private StockIncomeBillMapper stockIncomebillMapper;
    @Autowired
    private StockIncomeBillItemMapper stockIncomeBillItemMapper;
    @Autowired
    private ProductStockMapper productStockMapper;

    @Override
    public void saveOrUpdate(StockIncomeBill entity) {
        if (entity.getId() != null) {
            updateBill(entity);
        } else {
           saveBill(entity);
        }
    }
    //更新单据的业务操作
    private  void updateBill(StockIncomeBill entity){
        //判断当前单据必须是为审核状态
        StockIncomeBill old = stockIncomebillMapper.selectByPrimaryKey(entity.getId());
        //删除旧的明细插入新的明细
        if (old.getStatus() ==0) {
        stockIncomebillMapper.deleItemsByBillId(entity.getId());
            BigDecimal totalNumber = BigDecimal.ZERO;
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (StockIncomeBillItem item : entity.getItems()) {
                BigDecimal number = item.getNumber();
                BigDecimal amount = item.getCostPrice().multiply(number).setScale(2,RoundingMode.HALF_UP);
                totalNumber =totalNumber.add(number);
                totalAmount = totalAmount.add(amount);

                item.setBillId(entity.getId());
                item.setTotalAmount(amount);
                stockIncomeBillItemMapper.insert(item);
                //保存到数据库
            }
            old.setTotalNumber(totalNumber);
            old.setTotalAmount(totalAmount);
            old.setSn(entity.getSn());
            old.setVdate(entity.getVdate());
            old.setDepot(entity.getDepot());
            stockIncomebillMapper.updateByPrimaryKey(old);
        }
        //将新的数据设置到old
    }

    //新增单据的业务操作
    private  void saveBill(StockIncomeBill entity){
        //1.状态 2.录入人 3.录入时间
        entity.setStatus(StockIncomeBill.NOTAUDIT);
        entity.setInputUser(UserContext.getCurrentUser());
        entity.setInputTime(new Date());
        //entity.getId()
        //2:重新后台计算明细的小计
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (StockIncomeBillItem item : entity.getItems()) {
            BigDecimal number = item.getNumber();
            BigDecimal amount = item.getCostPrice().multiply(number).setScale(2,RoundingMode.HALF_UP);
            totalNumber =totalNumber.add(number);
            totalAmount = totalAmount.add(amount);

            //保存到数据库
        }
        entity.setTotalNumber(totalNumber);
        entity.setTotalAmount(totalAmount);
            stockIncomebillMapper.insert(entity);

        //先保存订单在保存明细
        for (StockIncomeBillItem item : entity.getItems()) {
            item.setBillId(entity.getId());
            BigDecimal number = item.getNumber();
            BigDecimal amount = item.getCostPrice().multiply(number).setScale(2,RoundingMode.HALF_UP);
            item.setTotalAmount(amount);
            stockIncomeBillItemMapper.insert(item);
        }

    }

    @Override
    public void delete(Long id) {
        if (id != null) {
            stockIncomebillMapper.deleItemsByBillId(id);
            stockIncomebillMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public StockIncomeBill get(Long id) {

            StockIncomeBill entity = stockIncomebillMapper.selectByPrimaryKey(id);
        return entity;

    }

    @Override
    public List<StockIncomeBill> selectall() {
        List<StockIncomeBill> depts = stockIncomebillMapper.selectAll();
        return depts;
    }

    @Override
    //审核
    public void audit(Long id) {

        //审核成功,需要将订单入库,改变库存量,
        //1.拿到订单明细
        StockIncomeBill stockIncomebill = stockIncomebillMapper.selectByPrimaryKey(id);
        //审核人 审核时间 状态
        stockIncomebill.setAuditor(UserContext.getCurrentUser());
        stockIncomebill.setAuditTime(new Date());
        stockIncomebill.setId(id);
        List<StockIncomeBillItem> items = stockIncomebill.getItems();
        Depot depot = stockIncomebill.getDepot();
        for (StockIncomeBillItem item : items) {
            BigDecimal totalNumber = BigDecimal.ZERO;
            BigDecimal totalAmount = BigDecimal.ZERO;
            //查询仓库内是否有同种商品库存
            //通过仓库和商品id来查询
            Product product = item.getProduct();
            //查询符合条件的条数
           ProductStock productStock = productStockMapper.selectByDepotIdAndProductId(depot.getId(),product.getId());
            //传入订单的商品小计 和数量
                BigDecimal amount = item.getCostPrice().multiply(item.getNumber()).setScale(2, RoundingMode.HALF_UP);
                     BigDecimal number = item.getNumber();
            if (productStock == null) {
                //仓库中没有同种商品
                //直接存入
                 productStock = new ProductStock();
                productStock.setStoreNumber(number);//库存量
                productStock.setPrice(item.getCostPrice());//库存价
                productStock.setAmount(amount);
                productStock.setProduct(product);
                productStock.setDepot(depot);
                productStockMapper.insert(productStock);
            }
            else {
                //仓库中有库存
             //有库存,使用移动加权平均算法(总价除总数量)
                //先查出已有的库存量和总价 重新计算后存入数据库
                //总数
                totalNumber= productStock.getStoreNumber().add(number);
                //总价
                totalAmount=productStock.getAmount().add(amount);
                //库存价
                BigDecimal price = totalAmount.divide(totalNumber, RoundingMode.HALF_UP);
                productStock.setStoreNumber(totalNumber);
                productStock.setAmount(totalAmount);
                productStock.setPrice(price);
                productStockMapper.updateByPrimaryKey(productStock);

            }


        }
        stockIncomebill.setStatus(StockIncomeBill.AUDIT);

        stockIncomebillMapper.audit(stockIncomebill);
    }

    @Override
    public PageResult queryForList(QueryObject qo) {
        int rows = stockIncomebillMapper.rows(qo);
        if (rows == 0) {
            return PageResult.EMPTY_RESULT;

        }
        PageResult result = new PageResult(qo.getCurrentPage(), qo.getPageSize(), rows, stockIncomebillMapper.queryForList(qo));
        System.out.println(66);
        return result;

    }
}
